#include "../../include/handler/handler.hpp"
#include "iostream"
using std::cout;
using std::endl;
namespace handler{



    // 在这里更新screen内容
    template<typename worldType>
    void AllSonHandler(drawer::Screen& screen,worldType& world){
        // for(auto x=100;x<=400;x++){
        //     for(auto y=0;y<100;y++){
        //         screen.updateScreenPixel(x,y,0.1f,1,1);
        //     }
        // }

        // 第一步为处理输入产生的变化


        // 第二步为进行光栅化
        //drawer::Raster::rasterizeDot(screen,world);
        std::cout<<"error, please use specific son handler";
    }
    template<>
    void AllSonHandler<object::World>(drawer::Screen& screen,object::World& world){
        drawer::Raster::rasterizeDot(screen,world);
    }

    template<>
    void AllSonHandler<object::ColorWorld>(drawer::Screen& screen,object::ColorWorld& world){
        drawer::Raster::rasterizeColorTriangleWithZBuffer(screen,world);
    }
        



    // 控制住每次的时间固定
    template<typename worldType>void MainHandler(drawer::Screen& screen, std::mutex& screen_mutex, worldType& world) {
    while (true) {
        // 获取开始时间
        auto start = std::chrono::steady_clock::now();
        {
            // 锁住互斥锁保护 shared data
            std::lock_guard<std::mutex> guard(screen_mutex);
            // 设置最大允许执行时间
            auto max_duration = std::chrono::milliseconds(MSPF);
            auto handler_start = std::chrono::steady_clock::now();

            AllSonHandler(screen, world);

            auto handler_end = std::chrono::steady_clock::now();
            auto handler_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(handler_end - handler_start);

            if (handler_elapsed > max_duration) {
                std::cerr << "Warning: AllSonHandler execution took too long!" << std::endl;
            }
        }
        // 获取当前时间
        auto end = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
        auto duration = std::chrono::milliseconds(MSPF);
        if (elapsed < duration) {
            std::this_thread::sleep_for(duration - elapsed);
        }
    }
}

    template void MainHandler<object::ColorWorld>(drawer::Screen& screen, std::mutex& screen_mutex, object::ColorWorld& world);

    template void MainHandler<object::World>(drawer::Screen& screen, std::mutex& screen_mutex, object::World& world);

}